/**
 * MTitle.js v1.0
 * Created by lifanko on 2019/7/28.
 * https://gitee.com/lifanko/MTitle
 */
class MTitle {
    constructor(title = 'MTitle', space = 1) {
        this.mtitle = title;
        this.space = space;

        this.timer = null;

        this.addSpace();
    }

    newTitle(title = 'MTitle') {
        this.mtitle = title;

        this.addSpace();
    }

    newSpace(space = 1) {
        this.space = space;

        this.addSpace();
    }

    addSpace() {
        let buffer = '';
        for (let i = 0; i < this.space; i++) {
            buffer += ' ';
        }

        this.title = this.mtitle + buffer + this.mtitle;
        this.length = this.mtitle.length + this.space;

        this.index = 0;
    }

    stop(reset = false) {
        if (this.timer !== null) {
            clearInterval(this.timer);
            this.timer = null;
        }

        if (reset) {
            this.index = 0;
            this.move();
        }
    }

    move() {
        if (this.index >= this.length) {
            this.index = 0;
        }

        document.title = this.title.substr(this.index++, this.length);
    }

    start(interval = 1000) {
        if (this.timer === null) {
            let t = this;

            this.timer = setInterval(function () {
                t.move();
            }, interval);
        }
    }
}